// 1、数据的初始渲染
const productData = [
  {
    id: 1001,
    imgUrl: "./imgs/apple.png",
    title: "苹果",
    titleEn: "Apple",
    price: 2.99,
  },
  {
    id: 1002,
    imgUrl: "./imgs/beer.png",
    title: "啤酒",
    titleEn: "Beer",
    price: 14.99,
  },
  {
    id: 1003,
    imgUrl: "./imgs/milk.png",
    title: "牛奶",
    titleEn: "Milk",
    price: 4.99,
  },
  {
    id: 1004,
    imgUrl: "./imgs/doughnut.png",
    title: "甜甜圈",
    titleEn: "Doughnut",
    price: 19.99,
  },
  {
    id: 1005,
    imgUrl: "./imgs/bread.png",
    title: "面包",
    titleEn: "Bread",
    price: 3.99,
  },
  {
    id: 1006,
    imgUrl: "./imgs/aubergine.png",
    title: "茄子",
    titleEn: "Aubergine",
    price: 3.49,
  },
  {
    id: 1007,
    imgUrl: "./imgs/lettuce.png",
    title: "生菜",
    titleEn: "Lettuce",
    price: 2.99,
  },
  {
    id: 1008,
    imgUrl: "./imgs/flour.png",
    title: "谷物",
    titleEn: "Flour",
    price: 17.99,
  },
]
const prouctList = document.querySelector('#product-list');
const cartList = document.querySelector('#cart-list tbody');
const totalPrice = document.querySelector('.total span')

// 初始化商品列表
productData.forEach(item => {
  prouctList.insertAdjacentHTML('beforeend', `
    <li>
      <div class="img-box"> <img src="${item.imgUrl}" alt=""></div>
      <h4>${item.title}</h4>
      <h5>${item.titleEn}</h5>
      <h6>¥${item.price}</h6>
      <button class="btn" prod-id="${item.id}">加入购物车</button>
    </li>
  `)
})
// 初始化购物车列表
const cartData = getCookie('cartData') && JSON.parse(getCookie('cartData')) || []
cartData.forEach(item => {
  insertItemToCart(item)
})
calculatePrice()

// 点击添加按钮，向购物车中添加商品
prouctList.addEventListener('click', function (e) {
  const target = e.target
  if (target.tagName == 'BUTTON') {
    // 1、获取添加按钮对应的商品信息
    const prodId = target.getAttribute('prod-id')
    const product = productData.find(item => {
      return item.id == prodId
    })
    // 判断购物车中是否已有改商品
    const productFromCart = cartData.find(item => {
      return item.id == prodId
    })
    if (productFromCart) {// 如果购物车中有该商品  --- 修改数量
      // 更新dom中的数量
      const quantityInput = document.querySelector('#prod-' + product.id + ' input')
      quantityInput.value = ++productFromCart.quantity
    } else {// 购物车中没有该商品 --- 加新结构
      // 2、根据商品信息生成相应的dom结构，插入到购物车列表中
      product.quantity = 1
      insertItemToCart(product)
      // 3、购物车数据更新
      cartData.push(product)
    }
    updateData()
  }
}, false)


// 删除
cartList.addEventListener('click', function (e) {
  const target = e.target
  if (target.tagName == 'BUTTON') {
    if (confirm('确认删除吗？')) {
      const tr = target.parentNode.parentNode
      // 删除数据
      /* 
      找到id
      根据id找到cartData中的数据对应的索引
      把对应的数据删掉
      */
      const id = tr.id.split('-')[1]
      const index = cartData.findIndex(item => {
        return item.id = id
      })
      cartData.splice(index, 1)
      updateData()
      // 删除dom
      tr.remove()
    }
  }
}, false)

// 修改数量
cartList.addEventListener('input', function (e) {
  if (target.tagName == 'INPUT') {
    const target = e.target
    const tr = target.parentNode.parentNode
    const id = tr.id.split('-')[1]
    cartData.forEach(item => {
      if (item.id == id) {
        item.quantity = target.value
      }
    })
    updateData()
  }
}, false)

function insertItemToCart(product) {
  cartList.insertAdjacentHTML('beforeend', `
    <tr id="prod-${product.id}">
      <td class="item">
        <img src="${product.imgUrl}" alt="">
        <p>${product.title}</p>
      </td>
      <td class="price">
        <p>¥${product.price}</p>
      </td>
      <td class="quantity">
        <input value="${product.quantity}" type="number" name="" id="">
      </td>
      <td class="delete">
        <button>X</button>
      </td>
    </tr>
  `)
}
function calculatePrice() {
  let res = 0
  cartData.forEach(item => {
    res += item.quantity * item.price
  })
  totalPrice.innerHTML = '¥' + res.toFixed(2)
}

function updateData() {
  setCookie('cartData', JSON.stringify(cartData))
  calculatePrice()
}

// // js对象 =》  字符串
// JSON.stringify(cartData)

// //  Json字符串 =》 js对象
// JSON.parse('Json字符串')